package com.wanxiang.commonlib.utils;
import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.ThreadUtils;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/*
isMainThread            : 判断当前是否主线程
getFixedPool            : 获取固定线程池
getSinglePool           : 获取单线程池
getCachedPool           : 获取缓冲线程池
getIoPool               : 获取 IO 线程池
getCpuPool              : 获取 CPU 线程池
executeByFixed          : 在固定线程池执行任务
executeByFixedWithDelay : 在固定线程池延时执行任务
executeByFixedAtFixRate : 在固定线程池按固定频率执行任务
executeBySingle         : 在单线程池执行任务
executeBySingleWithDelay: 在单线程池延时执行任务
executeBySingleAtFixRate: 在单线程池按固定频率执行任务
executeByCached         : 在缓冲线程池执行任务
executeByCachedWithDelay: 在缓冲线程池延时执行任务
executeByCachedAtFixRate: 在缓冲线程池按固定频率执行任务
executeByIo             : 在 IO 线程池执行任务
executeByIoWithDelay    : 在 IO 线程池延时执行任务
executeByIoAtFixRate    : 在 IO 线程池按固定频率执行任务
executeByCpu            : 在 CPU 线程池执行任务
executeByCpuWithDelay   : 在 CPU 线程池延时执行任务
executeByCpuAtFixRate   : 在 CPU 线程池按固定频率执行任务
executeByCustom         : 在自定义线程池执行任务
executeByCustomWithDelay: 在自定义线程池延时执行任务
executeByCustomAtFixRate: 在自定义线程池按固定频率执行任务
cancel                  : 取消任务的执行
 */
public class ThreadPoolUtils {

    private ThreadPoolExecutor pool = null;

       ThreadPoolExecutor executor;

    private ThreadPoolUtils() {
    executor = getNewInstance(2,4,"HRS_RUN",5);


    }

    public ThreadPoolExecutor getExecutor() {
        return executor;
    }

    public void setExecutor(ThreadPoolExecutor executor) {
        this.executor = executor;
    }

    public static ThreadPoolUtils getInstance() {
        return ThreadPoolUtils.SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static ThreadPoolUtils instance = new ThreadPoolUtils();
    }
    
    
    
    
    
    /**
     * 获取对象
     * @param corePoolSize 核心线程数量
     * @param poolName 线程池名称
     * @param maxThreadSize 最大线程数
     * @param maxTaskSize 最大阻塞任务数
     * @return
     */
    public ThreadPoolExecutor getNewInstance(int corePoolSize,int maxThreadSize,String poolName,int maxTaskSize){

        pool = createPool(corePoolSize,maxThreadSize,poolName,maxTaskSize);

        if(pool==null){
            throw new NullPointerException();
        }else{
            return pool;
        }
     }

    /**
     * 创建线程池
     * @param corePoolSize 核心线程数量
     * @param poolName 线程池名称
     * @param maxThreadSize 最大线程数
     * @param maxTaskSize 最大阻塞任务数
     * @return
     */
    private ThreadPoolExecutor createPool(int corePoolSize,int maxThreadSize,String poolName,int maxTaskSize){

        return new ThreadPoolExecutor(corePoolSize,maxThreadSize,0,
                TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(maxTaskSize),
                new CustomThreadFactory(poolName),
                new RejectedExecutionHandlerImpl());
    }

    /**
     * 线程工厂
     * 给线程命名
     */
    private class CustomThreadFactory implements ThreadFactory{

        private final String poolName;

        public CustomThreadFactory(String poolName){
            this.poolName = poolName;
        }

        private AtomicInteger count = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            String nowThreadName = "";
            nowThreadName = poolName + count.addAndGet(1);
            t.setName(nowThreadName);
            return t;
        }
    }

    /**
     * 自定义拒绝策略
     */
    private class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try{
                System.out.println("重回队列");
                executor.getQueue().put(r);
            }catch (Exception e){

            }
        }
    }

//    public static void main(String[] args){
//        ThreadPoolExecutor executor = new ThreadPoolUtils().getNewInstance(3,8,"test",5);
//        for (int i = 0;i<20;i++){
//            System.out.println("提交第"+i+"个任务");
//            executor.execute(()->{
//                try {
//                    System.out.println(Thread.currentThread().getName());
//                    TimeUnit.SECONDS.sleep(10);
//                    synchronized (num){
//                        System.out.println("数字为："+num++);
//                    }
//
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            });
//            System.out.println("提交第"+i+"个任务成功");
//        }
//        System.out.println("结束");
//    }
}
